<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Button,
  Col,
  DatePicker,
  Descriptions,
  DescriptionsItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  completeService as completeServiceApi,
  confirmBooking as confirmBookingApi,
  getBookingList,
  getBusinessContexts,
  markNoShow as markNoShowApi,
  startService as startServiceApi,
} from '#/api/booking';

const loading = ref(false);
const bookings = ref([]);
const businessContexts = ref([]);
const dateRange = ref<any>(undefined);

// 详情弹窗相关
const detailVisible = ref(false);
const selectedBooking = ref<any>(null);

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  contextId: '',
  status: '',
  customerName: '',
  startDate: '',
  endDate: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
});

// 表格列定义
const bookingColumns = [
  {
    title: '预约号',
    dataIndex: 'bookingNo',
    key: 'bookingNo',
    width: 120,
  },
  {
    title: '客户姓名',
    dataIndex: 'customerName',
    key: 'customerName',
    width: 100,
  },
  {
    title: '手机号',
    dataIndex: 'phoneNumber',
    key: 'phoneNumber',
    width: 120,
  },
  {
    title: '服务项目',
    dataIndex: 'serviceName',
    key: 'serviceName',
    width: 150,
  },
  {
    title: '预约时间',
    dataIndex: 'bookingDate',
    key: 'bookingDate',
    width: 120,
    customRender: ({ text, record }: any) => `${text} ${record.timeSlot}`,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '取号',
    dataIndex: 'queueTicket',
    key: 'queueTicket',
    width: 80,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

const loadBookings = async () => {
  try {
    loading.value = true;
    const result = await getBookingList(queryParams);
    bookings.value = result.list;
    pagination.total = result.total;
  } catch (error) {
    console.error('加载预约列表失败:', error);
    message.error('加载预约列表失败');
  } finally {
    loading.value = false;
  }
};

const loadBusinessContexts = async () => {
  try {
    const contexts = await getBusinessContexts();
    businessContexts.value = contexts;
  } catch (error) {
    console.error('加载业务场景失败:', error);
  }
};

const handleDateChange = (dates: any) => {
  if (dates && dates.length === 2) {
    queryParams.startDate = dayjs(dates[0]).format('YYYY-MM-DD');
    queryParams.endDate = dayjs(dates[1]).format('YYYY-MM-DD');
  } else {
    queryParams.startDate = '';
    queryParams.endDate = '';
  }
  loadBookings();
};

const handleTableChange = (pag: any) => {
  queryParams.page = pag.current;
  queryParams.pageSize = pag.pageSize;
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadBookings();
};

const confirmBooking = async (record: any) => {
  try {
    await confirmBookingApi(record.id);
    message.success('预约已确认');
    loadBookings();
  } catch (error) {
    console.error('确认预约失败:', error);
    message.error('确认预约失败');
  }
};

const startService = async (record: any) => {
  try {
    await startServiceApi(record.id);
    message.success('服务已开始');
    loadBookings();
  } catch (error) {
    console.error('开始服务失败:', error);
    message.error('开始服务失败');
  }
};

const completeService = async (record: any) => {
  try {
    await completeServiceApi(record.id);
    message.success('服务已完成');
    loadBookings();
  } catch (error) {
    console.error('完成服务失败:', error);
    message.error('完成服务失败');
  }
};

// 标记爽约
const markNoShow = async (record: any) => {
  try {
    await markNoShowApi(record.id);
    message.success('已标记为爽约');
    loadBookings();
  } catch (error) {
    console.error('标记爽约失败:', error);
    message.error('标记爽约失败');
  }
};

const viewBookingDetail = (record: any) => {
  selectedBooking.value = record;
  detailVisible.value = true;
};

const closeDetail = () => {
  detailVisible.value = false;
  selectedBooking.value = null;
};

const getBookingStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'orange',
    CONFIRMED: 'blue',
    IN_PROGRESS: 'green',
    COMPLETED: 'default',
    CANCELLED: 'red',
    NO_SHOW: 'red',
  };
  return colorMap[status] || 'default';
};

const getBookingStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    PENDING: '待确认',
    CONFIRMED: '已确认',
    IN_PROGRESS: '进行中',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
    NO_SHOW: '爽约',
  };
  return textMap[status] || '未知';
};

onMounted(() => {
  loadBusinessContexts();
  loadBookings();
});
</script>

<template>
  <div class="booking-list-admin">
    <Page title="预约列表管理" content="管理所有预约记录">
      <div class="admin-container">
        <!-- 筛选条件 -->
        <div class="filters-section">
          <Row :gutter="16">
            <Col :span="6">
              <Select
                v-model:value="queryParams.contextId"
                placeholder="选择业务场景"
                allow-clear
                @change="loadBookings"
              >
                <SelectOption
                  v-for="context in businessContexts"
                  :key="context.id"
                  :value="context.id"
                >
                  {{ context.name }}
                </SelectOption>
              </Select>
            </Col>
            <Col :span="6">
              <Select
                v-model:value="queryParams.status"
                placeholder="预约状态"
                allow-clear
                @change="loadBookings"
              >
                <SelectOption value="PENDING">待确认</SelectOption>
                <SelectOption value="CONFIRMED">已确认</SelectOption>
                <SelectOption value="IN_PROGRESS">进行中</SelectOption>
                <SelectOption value="COMPLETED">已完成</SelectOption>
                <SelectOption value="CANCELLED">已取消</SelectOption>
              </Select>
            </Col>
            <Col :span="6">
              <DatePicker.RangePicker
                v-model:value="dateRange"
                :placeholder="['开始日期', '结束日期']"
                @change="handleDateChange"
              />
            </Col>
            <Col :span="6">
              <Input
                v-model:value="queryParams.customerName"
                placeholder="客户姓名"
                @press-enter="loadBookings"
              />
            </Col>
          </Row>
        </div>

        <!-- 预约列表 -->
        <Table
          :columns="bookingColumns"
          :data-source="bookings"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          row-key="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <Tag :color="getBookingStatusColor(record.status)">
                {{ getBookingStatusText(record.status) }}
              </Tag>
            </template>

            <template v-else-if="column.key === 'actions'">
              <Space>
                <Button
                  v-if="record.status === 'PENDING'"
                  type="primary"
                  size="small"
                  @click="confirmBooking(record)"
                >
                  确认
                </Button>
                <Button
                  v-if="record.status === 'CONFIRMED'"
                  type="default"
                  size="small"
                  @click="startService(record)"
                >
                  开始服务
                </Button>
                <Button
                  v-if="record.status === 'IN_PROGRESS'"
                  type="success"
                  size="small"
                  @click="completeService(record)"
                >
                  完成
                </Button>
                <Button
                  v-if="
                    record.status === 'CONFIRMED' || record.status === 'PENDING'
                  "
                  type="warning"
                  size="small"
                  @click="markNoShow(record)"
                >
                  爽约
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="viewBookingDetail(record)"
                >
                  详情
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </div>

      <!-- 预约详情弹窗 -->
      <Modal
        v-model:open="detailVisible"
        title="预约详情"
        width="800px"
        :footer="null"
        @cancel="closeDetail"
      >
        <div v-if="selectedBooking" class="booking-detail">
          <Descriptions :column="2" bordered>
            <DescriptionsItem label="预约号">
              {{ selectedBooking.bookingNo }}
            </DescriptionsItem>
            <DescriptionsItem label="预约状态">
              <Tag :color="getBookingStatusColor(selectedBooking.status)">
                {{ getBookingStatusText(selectedBooking.status) }}
              </Tag>
            </DescriptionsItem>
            <DescriptionsItem label="客户姓名">
              {{ selectedBooking.customerName }}
            </DescriptionsItem>
            <DescriptionsItem label="手机号">
              {{ selectedBooking.phoneNumber }}
            </DescriptionsItem>
            <DescriptionsItem label="微信ID">
              {{ selectedBooking.wechatId || '--' }}
            </DescriptionsItem>
            <DescriptionsItem label="会员卡号">
              {{ selectedBooking.memberCard || '--' }}
            </DescriptionsItem>
            <DescriptionsItem label="业务场景">
              {{ selectedBooking.contextName }}
            </DescriptionsItem>
            <DescriptionsItem label="服务项目">
              {{ selectedBooking.serviceName }}
            </DescriptionsItem>
            <DescriptionsItem label="预约日期">
              {{ selectedBooking.bookingDate }}
            </DescriptionsItem>
            <DescriptionsItem label="预约时段">
              {{ selectedBooking.timeSlot }}
            </DescriptionsItem>
            <DescriptionsItem label="取号">
              {{ selectedBooking.queueTicket || '未取号' }}
            </DescriptionsItem>
            <DescriptionsItem label="排队位置">
              {{ selectedBooking.queuePosition || '未排队' }}
            </DescriptionsItem>
            <DescriptionsItem label="预计等待">
              {{ selectedBooking.estimatedWaitTime || '--' }}
            </DescriptionsItem>
            <DescriptionsItem label="创建时间">
              {{ selectedBooking.createTime }}
            </DescriptionsItem>
            <DescriptionsItem label="更新时间">
              {{ selectedBooking.updateTime }}
            </DescriptionsItem>
            <DescriptionsItem label="备注" :span="2">
              {{ selectedBooking.remarks || '无' }}
            </DescriptionsItem>
          </Descriptions>

          <div
            class="detail-actions"
            style="margin-top: 20px; text-align: center"
          >
            <Button @click="closeDetail">关闭</Button>
          </div>
        </div>
      </Modal>
    </Page>
  </div>
</template>

<style scoped>
.booking-list-admin {
  padding: 20px;
}

.admin-container {
  max-width: 1400px;
  margin: 0 auto;
}

.filters-section {
  padding: 20px;
  margin-bottom: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}
</style>
